package codec

import (
	"errors"
)

type message struct {
	ver  int32
	op 	 int32
	seq  int32
	body []byte
}


//Decode 解码一条消息
func (m *message)Decode(raw []byte) error {
	pos := 0
	//处理4字节的包长度
	packLen := BigEndian.Int32(raw[pos:pos+4])
	pos += 4
	//处理2个字节的头长度
	headerLen := BigEndian.Int16(raw[pos:pos+2])
	pos += 2
	//处理4个字节的ver
	m.ver = int32(BigEndian.Int16(raw[pos:pos+2]))
	pos += 2
	//处理4个字节的op
	m.op = BigEndian.Int32(raw[pos:pos+4])
	pos += 4
	//处理4个字节的seq
	m.seq = BigEndian.Int32(raw[pos:pos+4])
	pos += 4
	if packLen < 16 {
		return errors.New("illegal package length")
	}
	if headerLen != 16 {
		return errors.New("illegal header length")
	}

	//处理body
	m.body = raw[headerLen:packLen]
	return nil
}

//Encode
func (m *message)Encode() ([]byte, error) {
	packLen := int32(16 + len(m.body))
	pos := 0
	raw := make([]byte, packLen)

	//加入packLen
	BigEndian.PutInt32(raw[pos:], packLen)
	pos += 4
	//加入头长度
	BigEndian.PutInt16(raw[pos:], 16)
	pos += 2
	//加入ver
	BigEndian.PutInt16(raw[pos:], int16(m.ver))
	pos += 2
	//加入op
	BigEndian.PutInt32(raw[pos:], m.op)
	pos += 4
	//加入seq
	BigEndian.PutInt32(raw[pos:], m.seq)
	pos += 4
	//加入body
	copy(raw[pos:], m.body)



	return raw, nil
}



